//
//  RequestPlugin.swift
//  coin
//
//  Created by 刘泽 on 2017/12/14.
//  Copyright © 2017年 刘泽. All rights reserved.
//

import Foundation
import Moya
import Result
import SwiftyJSON


public let netWorkActivityPlugin = NetworkActivityPlugin { (change,target) -> () in
    
    switch(change){
    case .ended:
        
        UIApplication.shared.isNetworkActivityIndicatorVisible = false
    case .began:
        
        UIApplication.shared.isNetworkActivityIndicatorVisible = true
    }
}


public final class RequestLoadingPlugin: PluginType {
    
    private var loadingCount: Int = 0
    private let loadingQueue = DispatchQueue(label: "ToastLoadingQueue")

    public init() {

    }

    public func willSend(_ request: RequestType, target: TargetType) {
        //接口调用超过1秒 且无返回数据时显示加载中
        loadingQueue.asyncAfter(deadline: .now() + 1) {

            if self.loadingCount != 0{
                DispatchQueue.main.async {
                    Toast.showLoading()
                }
            }
        }
        

        loadingCount += 1

    }


    public func didReceive(_ result: Result<Response, MoyaError>, target: TargetType) {
        loadingCount -= 1
        if loadingCount == 0{
            Toast.hide()
        }
        handle(result, target: target)

    }
    
}


public final class RequestPlugin: PluginType {
    
    
    
    public func willSend(_ request: RequestType, target: TargetType) {
        
        
    }
    
    
    public func didReceive(_ result: Result<Response, MoyaError>, target: TargetType) {
        handle(result, target: target)

    }
    
}



public final class NoToastRequestLoadingPlugin: PluginType {

    private var loadingCount = 0
    private let loadingQueue = DispatchQueue(label: "ToastLoadingQueue")

    public init() {

    }

    public func willSend(_ request: RequestType, target: TargetType) {
        loadingQueue.asyncAfter(deadline: .now() + 0.3) {

            if self.loadingCount != 0{//接口调用超过0.3秒 且无返回数据时显示加载中
                DispatchQueue.main.async {
                    Toast.showLoading()
                }
            }
        }

        loadingCount += 1
        
    }
    
    
    public func didReceive(_ result: Result<Response, MoyaError>, target: TargetType) {
        loadingCount -= 1
        if loadingCount == 0{
            Toast.hide()
        }
        handle(result, target: target)
        
    }
    
}


public final class NoToastRequestPlugin: PluginType {
    
    public init() {

    }
    
    public func willSend(_ request: RequestType, target: TargetType) {
        
        
    }
    
    
    public func didReceive(_ result: Result<Response, MoyaError>, target: TargetType) {
        handle(result, target: target)
    }
    
}

extension PluginType{
    fileprivate func handle(_ result: Result<Response, MoyaError>, target: TargetType){
        ssPrint("请求连接：\(target.baseURL)\(target.path)")
        ssPrint("方法：\(target.method)")
        ssPrint("请求头:",target.headers ?? 0)
        ssPrint("参数：",target.task)
        switch result {

        case .success(let response):

            var json : JSON?
            do{
                json = try JSON(data: response.data)
                ssPrint(json ?? "json解析失败")
            }catch let error {
                ssPrint(error)
                ssPrint("数据解析失败")
            }

            switch response.statusCode{
            case 200:
                ssPrint("加载成功")
            case 400:
                ssPrint("参数错误")
            case 401:
                Toast.showMessage("登录已过期")
                return
            default:
                ssPrint("加载失败")
                Toast.showError("未知错误")
                ssPrint("加载失败\(response.statusCode)")
            }

            if let respo = try? response.mapJSON(){
                if let error = Mapper<MyError>().map(JSONObject: respo ) {
                    if error.error != nil{
                        Toast.showMessage(error.error!)
                        return
                    }
                }
            }

        case .failure:
            Toast.showError("网络异常")
            break
        }

    }
}
